package com.example.demo.controller;

import com.example.demo.model.InviteCode;
import com.example.demo.model.User;
import com.example.demo.service.InviteCodeService;
import com.example.demo.model.UserCredit;
import com.example.demo.service.UserService;
import com.example.demo.utils.JwtUtils;
import com.example.demo.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/api/auth")
public class AuthController {
    private final UserService userService;
    private final AuthenticationManager authenticationManager;
    private final JwtUtils jwtUtils;
    private final InviteCodeService inviteCodeService;

    @Autowired
    public AuthController(UserService userService,
                          AuthenticationManager authenticationManager,
                          JwtUtils jwtUtils,
                          InviteCodeService inviteCodeService) {
        this.userService = userService;
        this.authenticationManager = authenticationManager;
        this.jwtUtils = jwtUtils;
        this.inviteCodeService = inviteCodeService;
    }

    @PostMapping("/login")
    @ResponseBody
    public ResponseEntity<?> login(@RequestBody Map<String, String> loginRequest) {
        String email = loginRequest.get("email");
        String password = loginRequest.get("password");


        User user = userService.findByEmail(email);
        if (user == null) {
            return ResponseEntity.status(401).body(Map.of(
                    "status", "error",
                    "message", "用户名或密码错误"
            ));
        } else if (userService.getBanStatusByEmail(email)) {
            return ResponseEntity.status(200).body(Map.of(
                    "status", "error",
                    "message", "账户已被封禁",
                    "id", user.getId()
            ));
        }

        try {
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(user.getUsername(), password)
            );
            SecurityContextHolder.getContext().setAuthentication(authentication);
            System.out.println("认证成功: " + authentication.getName());
            System.out.println("用户角色: " + authentication.getAuthorities());

            // 生成 JWT Token
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            String token = jwtUtils.generateToken(userDetails,user.getId(),user.getEmail());
            System.out.println("生成 Token: " + token);

            return ResponseEntity.ok(Map.of(
                    "status", "success",
                    "message", "登录成功",
                    "token", token,
                    "id", user.getId(),
                    "username", user.getUsername(),
                    "email", user.getEmail()
            ));
        } catch (Exception e) {
            return ResponseEntity.status(401).body(Map.of(
                    "status", "error",
                    "message", "用户名或密码错误"
            ));
        }
    }

    @PostMapping("/register_code")
    @ResponseBody
    public Response<String> sendVerificationCode(@RequestBody Map<String, String> registerRequest) {
        String email = registerRequest.get("email");
        try {
            userService.sendVerificationCode(email);
            return Response.success("验证码已发送至邮箱，请注意查收。");
        } catch (Exception e) {
            return Response.fail(Response.INTERNAL_SERVER_ERROR, "验证码发送失败，请稍后再试。");
        }
    }

    @GetMapping("/login")
    public String loginForm() {
        return "redirect:/login.html";
    }

    @GetMapping("/register")
    public String registerForm(Model model) {
        model.addAttribute("user", new User());
        return "register";
    }

    @PostMapping("/register")
    @ResponseBody
    public ResponseEntity<?> registerUser(@RequestBody User user,
                                          @RequestParam("code") String code,
                                          @RequestParam("inviteCode") String inviteCode) {
        try {
            System.out.println(code + inviteCode);
            //邮箱重复校验
            if (userService.findByEmail(user.getEmail()) != null) {
                return ResponseEntity.badRequest().body(Map.of(
                        "status", "error",
                        "message", "邮箱已被注册"
                ));
            }
            userService.registerUser(user, code, inviteCode);
            return ResponseEntity.ok().body(Map.of(
                    "status", "success",
                    "message", "用户注册成功"
            ));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of(
                    "status", "error",
                    "message", e.getMessage() != null ? e.getMessage() : "未知错误"
            ));
        }
    }

    // 临时允许匿名访问管理员注册
    @PostMapping("/register-admin-init")
    public Response<String> initAdminAccount(
            @RequestBody User adminUser,
            @RequestParam String code) {
        // 添加验证逻辑，如特定初始化密钥
        if (!"YOUR_INIT_SECRET_KEY".equals(code)) {
            return Response.forbidden("非法初始化请求");
        }

        userService.registerAdmin(adminUser, code);
        return Response.success("初始管理员创建成功");
    }

    @PostMapping("/register-admin")
//    @PreAuthorize("hasRole('ADMIN')") // 只有现有管理员能创建新管理员
    public Response<String> registerAdmin(
            @RequestBody User adminUser,
            @RequestParam String code) {
        try {
            userService.registerAdmin(adminUser, code);
            return Response.success("管理员账户创建成功");
        } catch (Exception e) {
            return Response.fail(Response.BAD_REQUEST, e.getMessage());
        }
    }

    @PostMapping("/forgot-password")
    @ResponseBody
    public ResponseEntity<?> forgotPassword(@RequestParam String email,
                                            @RequestParam String code,
                                            @RequestParam String password) {
        try {
            userService.forgetPassword(email, code, password);
            return ResponseEntity.ok().body(Map.of(
                    "status", "success",
                    "message", "密码修改成功"
            ));
        } catch (RuntimeException e) {
            // 返回具体的错误信息和 400 Bad Request 状态码
            return ResponseEntity.badRequest().body(Map.of(
                    "status", "error",
                    "message", e.getMessage()
            ));
        }
    }

    @GetMapping("/userinfo")
    @ResponseBody
    public ResponseEntity<?> getUserInfo(@RequestHeader("Authorization") String authHeader) {
        try {
            String token = authHeader.substring(7); // 去掉"Bearer "前缀

            // 从Token中获取用户信息
            Long userId = jwtUtils.getUserIdFromToken(token);
            String email = jwtUtils.getEmailFromToken(token);
            String username = jwtUtils.getUsernameFromToken(token);

            return ResponseEntity.ok(Map.of(
                    "status", "success",
                    "data", Map.of(
                            "id", userId,
                            "username", username,
                            "email", email
                    )
            ));
        } catch (Exception e) {
            return ResponseEntity.status(401).body(Map.of(
                    "status", "error",
                    "message", "无效的token或token已过期"
            ));
        }
    }

    @PostMapping("/reset-password")
    @ResponseBody
    public ResponseEntity<?> resetPassword(@RequestBody Map<String, String> request) {
        String token = request.get("token");
        String newPassword = request.get("newPassword");

        try {
            userService.completePasswordReset(token, newPassword);
            return ResponseEntity.ok(Map.of(
                    "status", "success",
                    "message", "密码重置成功"
            ));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                    "status", "error",
                    "message", e.getMessage()
            ));
        }
    }
    @GetMapping("/user/{token}")
    @ResponseBody
    public ResponseEntity<?> getUser(@RequestHeader("Authorization") String authHeader, @PathVariable("token") String tokens) {
        try {
            String token = authHeader.substring(7); // 去掉"Bearer "前缀

            // 从Token中获取用户信息
            String email = jwtUtils.getEmailFromToken(token);
            System.out.println("email: " + email);

            User user = userService.findByEmail(email);
            UserCredit userCredit = userService.getUserCredit(user.getId());
            System.out.println("user"+user.getUsername());
            return ResponseEntity.ok(Map.of(
                    "status", "success",
                    "data", Map.of(
                            "id", user.getId(),
                            "username", user.getUsername(),
                            "email", user.getEmail(),
                            "level", 1,
                            "upload",user.getUpload(),
                            "download", user.getDownload(),
                            "ratio", user.getShareRating(),
                            "score", userCredit.getBalance(),
                            "yangtao", 42
                    )
            ));
        } catch (Exception e) {
            return ResponseEntity.status(401).body(Map.of(
                    "status", "error",
                    "message", "无效的token或token已过期"
            ));
        }
    }

    @GetMapping("/other-user/{id}")
    @ResponseBody
    public ResponseEntity<?> getUserById(@PathVariable("id") Long id) {
        User user = userService.findById(id);
        return ResponseEntity.ok(user);

    }

    @GetMapping("/home")
    @ResponseBody
    public String home() {
        return "登录成功！欢迎访问主页。";
    }
}